package org.basis.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * 阻塞server测试
 *
 * @author Mr_wenpan@163.com 2021/09/14 17:42
 */
@Slf4j
public class BlockServer {

    public static void main(String[] args) throws IOException {
        // 服务端的socketchannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 设置这个ServerSocketChannel为非阻塞
        ssc.configureBlocking(false);
        List<SocketChannel> list = new ArrayList<>();

        while (true) {
            // 阻塞接收客户端连接
            SocketChannel sc = ssc.accept();
            sc.configureBlocking(false);
            list.add(sc);

            for (int i = 0; i < list.size(); i++) {
                SocketChannel channel = list.get(i);
                ByteBuffer buffer = ByteBuffer.allocate(16);
                // 阻塞方法
                channel.read(buffer);
                buffer.flip();
                // 将buffer中的内容读取出来
                System.out.println(Charset.defaultCharset().decode(buffer));
            }

        }

    }
}
